package xyz.heyaoshare.core.service.system.impl;

import com.mybatisflex.spring.service.impl.CacheableServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.heyaoshare.common.constants.CacheKey;
import xyz.heyaoshare.core.entity.system.Logs;
import xyz.heyaoshare.core.mapper.system.LogsMapper;
import xyz.heyaoshare.core.service.system.LogsService;

import static xyz.heyaoshare.exceptions.code.ErrorInfo.LOG_SAVE_FAILED;
import static xyz.heyaoshare.exceptions.customize.ServerException.exception;

/**
 * 日志 Service 实现类
 * @author YueHe
 * @version 0.0.1
 * @since 2025/6/25 下午2:06
 */
@Slf4j
@Service
@CacheConfig(cacheNames = CacheKey.LOGS_SERVICE)
public class LogsServiceImpl extends CacheableServiceImpl<LogsMapper, Logs> implements LogsService {

    @Lazy
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveLogs(Logs logs, Boolean isAsync) {
        // 异步保存日志
        if (isAsync == null || isAsync) {
            taskExecutor.execute(() -> {
                try {
                    save(logs);
                } catch (Exception e) {
                    String string = logs.toString();
                    log.error("日志记录：{}", string.length() > 10000 ? string.substring(0, 10000) : string);
                    log.error("日志保存失败！", e);
                }
            });
            return;
        }

        // 同步保存日志
        try {
            save(logs);
        } catch (Exception e) {
            log.error("日志保存失败！", e);
            throw exception(LOG_SAVE_FAILED);
        }
    }

}